#coding:utf8
from config import *
import multiprocessing as mp  
from routin import *
import queue

mouse_input_q = queue.Queue()
def moving_other(a,cpos,x,y):
    if not cfg.x2_mode and is_left_to_x2() and a in cfg.left_mouse and cfg.w2showing:
        cfg.left_to_x2 = False
        into_x2_mode()
        cfg.sum = str(cfg.far[0])
        deal_x2_mode_num()
    if cfg.x2_mode:
        if cfg.x2_ini_mouse==0:
            if a in cfg.right_mouse:
                cfg.x2_ini_mouse = 2
            else:
                cfg.x2_ini_mouse = 1
        if cfg.x2_ini_mouse==1 and a in cfg.right_mouse and (cfg.x2_pressed or cfg.middle_pressed):
            cfg.x2_ini_mouse = 2
        if (cfg.x2_ini_mouse==2 and a in cfg.right_mouse) or (cfg.x2_ini_mouse==1 and a not in cfg.right_mouse):                
            if not pm.enter_pressed:
                deal_x2_move(x, y, a not in cfg.right_mouse)                
                find_near_d(True)
            else:
                pm.enter_other = True
        else:
            cfg.isShow = False
            clear(False)  
            cfg.x2_mode = False
            x, y = cpos
            cfg.move_task = (cfg.x2_mode_dst[0] - x,cfg.x2_mode_dst[1] - y, 2)
            cfg.move_task_time = time.time()        
            print('move_task', cfg.move_task)
    cfg.lock_xing_mode=0
    cfg.lock_xing_mode_one_time=False            

def writeThr():
    while 1:
        time.sleep(1)
        a=0
        if cfg.acc_add>liang_conf[0]:
            a=1
        f=open('cpu.txt','w')
        f.write(str(a))
        f.close()

qq = None
def handle_event(e): #: winrawin.RawInputEvent
    if str(e.name)=='middle' and str(e.event_type) == 'down':
        qq.put( ('mid',e.device.handle,0,0,0) )
    if str(e.name)=='right' and str(e.event_type) in('up', 'down'):
        qq.put( ('right',e.device.handle,0,0,0) )
    if str(e.name)=='left' and str(e.event_type) in('up', 'down'):
        qq.put( ('left',e.device.handle,0,0,0) )

    if str(e.name)=='thumb1' and str(e.code)=='4':
        if str(e.event_type)=='up':
            qq.put(( 't1up',e.device.handle,0,0,0))
        else:
            qq.put(( 't1down',e.device.handle,0,0,0))
    if str(e.name)=='thumb2' and str(e.code)=='5':
        if str(e.event_type)=='up':
            qq.put(( 't2up',e.device.handle,0,0,0))
        else:
            qq.put(( 't2down',e.device.handle,0,0,0))

    if e.event_type == 'move':
        qq.put(( 'm', e.device.handle, e.delta_x, e.delta_y, time.time()))
    if e.event_type == 'wheel-up':
        qq.put(( 'w', e.device.handle, int(e.code), e.delta_y, time.time()))
    if e.event_type == 'wheel-down':
        qq.put(( 'w', e.device.handle, -int(e.code), e.delta_y, time.time()))     
      
def pro_input(q):
    global qq
    qq = q
    import winrawin
    import tkinter as tk    
    window = tk.Tk()
    window.maxsize(200, 80)
    winrawin.hook_raw_input_for_window(window.winfo_id(), handle_event)
    window.mainloop()

def add_mouse(h):
    if h in cfg.left_mouse or h in cfg.right_mouse:
        return 
    ll = len(cfg.left_mouse)+len(cfg.right_mouse)
    if ll >=len(mouse_count):
        se = 0
    else:
        se = mouse_count[ll]
    if se==1:
        cfg.left_mouse.append(h)
    else:
        cfg.right_mouse.append(h)
    print('add mouse', cfg.left_mouse, cfg.right_mouse)   

def deal_wheel_ge2(x):
    dd=6
    if x<0:
        dd=-dd
    deal_manu_scroll(dd)

def deal_wheel_len(x):
    dd = wheel_len_scal*get_sc_size()
    if x<0:
        dd = -dd        
    to_lock.acquire()                    
    cfg.to = cut_to(cfg.to+dd)                            
    set_to_chg()
    to_lock.release()      

def deal_wheel_len2(x):
    dd = wheel_len_scal*get_sc_size()*0.5
    if x<0:
        dd = -dd        
    to_lock.acquire()                    
    cfg.to = cut_to(cfg.to+dd)                            
    set_to_chg()
    to_lock.release()   
def ini_wheel(x):
    cfg.sum = str(int(cfg.far[0]))
    deal_x2_mode_num()
    return

def deal_wheel(a,x):    
    cfg.ctrl2_other = True
    if cfg.middle_pressed and cfg.w2showing and not cfg.x2_mode:
        if not cfg.ctrl2_job:
            deal_wheel_ge2(x)
        else:
            deal_wheel_len2(x)
        cfg.scroll_one = 0            
        cfg.middle_pressed_other = True
        return
    
    if cfg.x2_pressed and cfg.x2_type==1 and cfg.w2showing:
        ori = cfg.x2_mode
        into_x2_mode()  
        cfg.has_update_cancle=True
        cfg.has_update_cancle_counter =False
        cfg.has_update_has_wheel = True
        cfg.x2_pressed_then_other = True
        if not ori:
            ini_wheel(x)
    if pm.enter_pressed:
        pm.enter_other = True
        return              

    if not cfg.x2_mode and cfg.w2showing and cfg.x2_pressed:
        if not cfg.x2_pressed_then_other:
            cfg.scroll_one+=1          
        cfg.x2_pressed_then_other = True
        cfg.middle_pressed_other = True        
    if not cfg.x2_mode and a in cfg.left_mouse:
        x = -x

    if cfg.x2_mode:                
        cfg.x2_pressed_then_other = True
        cfg.middle_pressed_other = True        
        dd = 100 / (len(cfg.snap) - 1)  
        if cfg.middle_pressed:
            dd *= 3
        if cfg.x2_pressed and cfg.x2_type==0:
            dd /=3
        if x>0:
            cfg.x2_mode_d +=  dd
        else:
            cfg.x2_mode_d -=  dd
        if cfg.x2_mode_d<0:
            cfg.x2_mode_d = 0                
        find_near_d()
        x2_d_to_dst()
        if a in cfg.right_mouse:
            cfg.x2_ini_mouse = 2
        else:
            cfg.x2_ini_mouse = 1
        return
    if x<0:
        cfg.min_ge = 0
        
    if a in cfg.right_mouse and not cfg.ctrl2_job:
        if is_sca():
            dd = 1
            if cfg.x2_pressed:
                dd = 3
            if x<0:
                dd = -dd
        else:
            dd = 3
            if cfg.scroll_one%2==1:
                dd=1
            if x<0:
                dd=-dd
        deal_manu_scroll(dd)

    else:
        if pm.scroll_pressed:
            pm.scroll_other = True
            deal_wheel_len2(x)
        else:
            deal_wheel_len(x)

def hou_click():
    if not cfg.w2showing:
        if cfg.jump_state==1:
            jump_state_chg(0)
            cfg.can_set_acc=True
            set_acc()
            return
        if cfg.min_ge==0:
            enter_ge_mode(3)
            if kuai_ge_chg:
                cfg.getokuai=100
            return
        enter_force()
        return
    if cfg.min_ge!=0 and not cfg.min_ge_force_show:
        cfg.min_ge=0
        cfg.show_mode=1
        cfg.left_to_x2 = False
        return
    if cfg.x2_mode:
        reset_x2_ini_and_slow()
        return
    update_du(True)        

def qian_click():
    from keyr import on_press
    if not cfg.w2showing:
        if cfg.sum=='0':            
            ori = cfg.jump_kuai
            clear(True)
            set_acc()     
            cfg.can_set_acc = True         
            if ori!=2:
                  kuai_into_2()
                #   cfg.jump_kuai=1
            else:
                acc_total()
            return                        
        cfg.pause_time=time.time()
        on_press(pause_str)
        return
    if not cfg.x2_mode:     
        do_into_x2()
        return
    x2_jump()    

def deal_hou():
    if cfg.jump_state==0:
        jump_state_chg(1)
    else:
        jump_state_chg(0)
        cfg.can_set_acc=True
    cfg.right_hou_has_other=True
                    
def check_to(a):    
    isx = True
    x1, y1, x2, y2 = a
    xx = x1 + x2
    yy = y1 + y2
    d3 = math.sqrt(xx * xx + yy * yy)
    d1 = math.sqrt(x1 * x1 + y1 * y1)
    d2 = math.sqrt(x2 * x2 + y2 * y2)
    du = math.atan2(y1, x1)
    du2 = math.atan2(y2, x2)
    d = du2 - du
    if d >  math.pi:
        d -= 2 * math.pi
    if d < - math.pi:
        d += 2 * math.pi   
    
    if d3 > max(d2 , d1):
        return 0,isx
    
    if d1 < 1 or d2 < 1:
        return 0,isx
        
    if abs(d) < math.pi * 0.5:
        return    0,isx
    a = -1
    
    if abs(x2) > abs(y2):
        if x2 > 0:
            a = 1
    else:
        isx = False
        if y2 > 0:
            a = 1    
    return a * max(d1, d2),isx

def one_loop():
    dx1 = 0
    dy1 = 0
    dx2 =0
    dy2 = 0    
    while not mouse_input_q.empty():               
        a = mouse_input_q.get()        
        h, x, y, t,isshow = a
        if not isshow:
            x = 0
            y =0
        if h in cfg.left_mouse:
            dx1 += x
            dy1 += y
        else:
            dx2 += x
            dy2 += y
    return dx1, dy1, dx2, dy2

def read_mouse_q_thr():        
    while True:
        time.sleep(0.05)
        a = one_loop()       
        dd,isx = check_to(a)       
        if dd == 0:
            continue
        if dd<0:
            cfg.min_ge = 0
        if not cfg.w2showing:
            continue        
        if (cfg.to <= 0 and dd < 0) or (cfg.to >= max_l and dd > 0):
            cfg.to_time = time.time()
            continue
        to_lock.acquire()        
        cfg.to = cut_to(cfg.to+dd*get_to_sca())
        cfg.to_time = time.time()
        if not is_sca() and cfg.auto_to_scale:
            update_du(True)            
        set_to_chg()        
        to_lock.release()                
def period_job():        
        if cfg.conkey:
            deal_conkey(cfg.conkey)
            cfg.conkey=''
            set_cfg_sum_0()

        if cfg.release_job!=0 and time.time()-cfg.release_job>0.02:
            mouse.Controller().release(mouse.Button.left)
            cfg.release_job=0
        if cfg.press_job>0 and time.time()-cfg.press_job>0.02:
            mouse.Controller().press(mouse.Button.left)  
            cfg.press_job=0

        if cfg.press_job<0 and time.time()+cfg.press_job>0.02:
            mouse.Controller().release(mouse.Button.left)
            cfg.press_job=0
        
        if cfg.jump_task!=None and not cfg.w2showing:
            if len(cfg.jump_task)==2:
                x,y = cfg.jump_task
                setf = False
                cl = True
            else:
                x,y,setf = cfg.jump_task            
                cl = False
            con_set_pos(cfg.jump_task[0],cfg.jump_task[1])
            if cl:
                clear(True)
            if setf:
                cfg.set_fix_time = time.time()
            cfg.jump_task = None

        if cfg.ctrl_job!=None and time.time()-cfg.ctrl_job_time>ctrl_double_gap:
            from routin_alt import ctrl_ini_imp
            ctrl_ini_imp(cfg.ctrl_job)
            cfg.ctrl_job = None

        if time.time() - cfg.set_fix_time < 0.02:
            if get_cur_pos() != cfg.fix_pos:
                print('diff', time.time() - cfg.set_fix_time, get_cur_pos(), cfg.fix_pos)
                cfg.fix_pos = get_cur_pos()
            
        if time.time() - cfg.click_time > 0.2 and cfg.click_time >= 0 and cfg.jump_task==None:
            cfg.click_time = -1
            mouse.Controller().click(mouse.Button.left)            

        if time.time() - cfg.click2_time > 0.2 and cfg.click2_time >= 0  and cfg.jump_task==None:
            cfg.click2_time = -1
            mouse.Controller().click(mouse.Button.left,2)            
            
        if cfg.move_task != None:
            dx, dy , ty= cfg.move_task
            d = move_task_delay1
            if ty == 2:
                d = move_task_delay2            
            if time.time() - cfg.last_move_time > d:            
                cfg.move_task = None
                clear_jump()
                x, y = get_cur_pos()
                cfg.fix_pos = (x + dx, y + dy)
                cfg.set_fix_time = time.time()
                try:
                    mouse.Controller().move(round(dx), round(dy))
                    deal_reset_one()
                    clear_mouse_mode()
                except Exception as e:
                    print(e)
    